$(document).ready(function () {
    var hotel_id = $("#hotel_id").val();
    $('#hotel-detail-map').bind('click', function (e) {
        e.preventDefault();
        $("#view-map-dynamic").bPopup();
        cm_load(hotel_id, 'hotel');
    });

    //Zoom in slide show
    $('.iFullScreen').on('click', function (e) {

        // Prevents the default action to be triggered.
        e.preventDefault();

        // Triggering bPopup when click event is fired
        $(this).parents(".large-desc").children("a").trigger("click");
    });
    $('.large-desc > a').lightBox({
        txtImage:"",
        txtOf:"/"
    });

    /*$('.large-desc').on('click', function (e) {
        // Prevents the default action to be triggered.
        e.preventDefault();
        // Triggering bPopup when click event is fired
        var content = $(this).attr('data-src');
        $('#full_' + content).bPopup({
            onOpen:function () {
                var tmp_prev = $(this).find("#sys_btn_prev_full_view");
                var tmp_next = $(this).find("#sys_btn_next_full_view");
                var size_order_imgs = $("#size_order_imgs");
                var length_slide = size_order_imgs.attr("data-val");
                if (content == 0) {
                    tmp_prev.hide();
                } else {
                    tmp_prev.show().on("click", function () {
                        $('#full_' + content).find("#sys_btn_prev_full_view").off("click");
                        $('#full_' + content).find("#sys_btn_next_full_view").off("click");
                        $('#full_' + content).bPopup().close();
                        var new_destination = parseInt(content) - 1;
                        $("#large_" + new_destination).trigger("click");
                    });
                }
                if (content == (length_slide - 1)) {
                    tmp_next.hide();
                } else {
                    tmp_next.show().on("click", function () {
                        $('#full_' + content).find("#sys_btn_prev_full_view").off("click");
                        $('#full_' + content).find("#sys_btn_next_full_view").off("click");
                        $('#full_' + content).bPopup().close();
                        var new_destination = parseInt(content) + 1;
                        $("#large_" + new_destination).trigger("click");
                    });
                }


            }
        });
    });*/

    //Jump in page
    $('.jumpinpage').click(function () {
        var jump = $(this).attr('data-val');
        var new_position = $('#' + jump).offset();
        window.scrollTo(new_position.left, new_position.top);
        return false;
    });

    //ĐẶT PHÒNG
    $(".bookhotel").click(function () {
        var hotel_id = $("#hotel_id").val();
        var from_date = $("#sys_txt_date_in1").val();
        var to_date = $("#sys_txt_date_out2").val();
        var thongtin = $(".sophong");
        var room = new Array();
        var dachon = false;
        for (var key = 0; key < thongtin.length; key++) {
            id = $(thongtin[key]).attr("data-key");
            if ($(thongtin[key]).val() != 0) {
                room[id] = $(thongtin[key]).val();
                dachon = true;
            }
        }
        if (dachon && hotel_id != '' && from_date != '' && to_date != '') {
            jQuery.post(WEB_DIR + "ajax.php?act=processcart&code=cart", {
                hotel_id:hotel_id,
                to_date:to_date,
                from_date:from_date,
                room:room,
                __okaToken:BASE_TOKEN
            }, function (msg) {
                if (msg.type == 1) {
                    $("#processcart").html(msg.item);
                } else if (msg.type == 0) {
                    alert(msg.message);
                } else if (msg.type == 2) {
                    $(".sign-in-popup").bPopup();
                }
            }, "json");
        }
        else {
            alert("Bạn chưa chọn số phòng muốn đặt!");
        }
    });

    //KIỂM TRA GIÁ PHÒNG
    $(".check_rates").click(function () {
        if ($("#sys_txt_date_in1_1").val() == '') {
            $('#sys_txt_date_in1_1').focus();
        } else if ($("#sys_txt_date_out2_1").val() == '') {
            $('#sys_txt_date_out2_1').focus();
        } else {
            var hotel_id = $("#hotel_id").val();
            var web_loc = $("#web_loc").val();

            if ($("#sys_txt_date_in1").val()) {
                var from_date = $("#sys_txt_date_in1").val();
                var to_date = $("#sys_txt_date_out2").val();
            } else {
                var from_date = $("#sys_txt_date_in1_1").val();
                var to_date = $("#sys_txt_date_out2_1").val();
            }

            if (from_date != '' && to_date != '') {
                var fd = datetostring(from_date);
                var td = datetostring(to_date);
                day = (td - fd);
//                console.log(day / 3600 / 24);
                if (day > 30 * 24 * 3600 * 1000) {
                    alert("Bạn không thể đặt quá 30 ngày !");
                } else {
                    document.location = web_loc + '/' + from_date + '/' + to_date + '#check-gia-phong';
                }
            }
        }
    });

    $(".sophong").change(function () {
        var a = $(this).attr("data-key");
        var b = $(this).val();
        if (b > 0) {
            $("#check_" + a).css("opacity", "1");
            $("#tr_" + a).attr("class", "active");
        } else {
            $("#check_" + a).css("opacity", "0");
            $("#tr_" + a).attr("class", "");
        }

        var c = $(this).attr("price-key");
        if (b != 0) {
            b = addPeriod(b * c);
        } else {
            b = addPeriod(c);
        }
        $("#price_" + a).text(b);

        var thongtin = $(".sophong");
        var total = 0;
        for (var key = 0; key < thongtin.length; key++) {
            if ($(thongtin[key]).val() != 0) {
                total = total + $(thongtin[key]).val() * $(thongtin[key]).attr("price-key");
            }
        }
        if (total == 0) {
            $("#tonggia").hide();
            $("#tongtien").hide();
            $(".bookhotel").css("opacity", "0.5");
            $(".bookhotel").css("cursor", "default");
        } else {
            $("#tonggia").show();
            $("#tongtien").show();
            $(".bookhotel").css("opacity", "1");
            $(".bookhotel").css("cursor", "pointer");

        }
        totalshow = addPeriod(total);
        $("#tongtien").text(totalshow + "đ");
    });

    //SLIDE
    var size_order_imgs = $("#size_order_imgs");
    var end = size_order_imgs.attr("data-val");
    end = end - 1;
    var index = 0;
//    console.log($(".large_img").attr("src"));
//    console.log(end);

    $(".slide-desc").mouseover(function () {
        if (end <= 0) {
            $(".prev").hide();
            $(".next").hide();
        } else {

            if (index == 0) {
                $(".prev").hide();
            } else {
                $(".prev").show();
            }
            if (index == end) {
                $(".next").hide();
            } else {
                $(".next").show();
            }
        }
    }).mouseout(function () {
            $(".prev").hide();
            $(".next").hide();
        });

    $(".thumb_icon").click(function () {
        var sl = $(this).attr("attr-key");
        $(".large-desc").hide();
        $("#large_" + sl).fadeIn(500);
        $(".active").removeClass("active");
        $(this).addClass("active");
        index = parseInt(sl);
//        console.log(index);
    });
    $(".next").click(function () {

        index = parseInt(index + 1);
        if (index == 0) {
            $(".prev").hide();
        } else {
            $(".prev").show();
        }
        if (index == end) {
            $(".next").hide();
        } else {
            $(".next").show();
        }
        if (index % 8 == 0) {
            $(".thumb_icon").hide();
            indexx = index + 8;
            if (indexx < end) {
                for (i = index; i < indexx; i++) {
                    $("#overview_" + i).show();
                }
            } else {
                endd = end - 7;
                for (i = endd; i <= end; i++) {
                    $("#overview_" + i).show();
                }
            }
        }
        $(".large-desc").hide();
        $("#large_" + index).fadeIn(500);
        $(".active").removeClass("active");
        $("#overview_" + index).addClass("active");
//        console.log(index);

    });

    $(".prev").click(function () {
        index = parseInt(index - 1);
        if (index == 0) {
            $(".prev").hide();
        } else {
            $(".prev").show();
        }
        if (index == end) {
            $(".next").hide();
        } else {
            $(".next").show();
        }
        if (index % 8 == 7) {
            $(".thumb_icon").hide();
            indexx = index - 8;
            for (i = indexx; i <= index; i++) {
                $("#overview_" + i).show();
            }
        }
        $(".large-desc").hide();
        $("#large_" + index).fadeIn(500);
        $(".active").removeClass("active");
        $("#overview_" + index).addClass("active");
    });

    //DATE PICKER

    jQuery("#sys_txt_date_in1, #sys_txt_date_in1_1").datepicker({
        dateFormat:"dd-mm-yy",
        changeMonth:false,
        firstDay:1,
        minDate:0,
        onSelect:function (selectedDate) {
            var selectDate = new Date(datetostring(selectedDate));
            selectDate.setDate(selectDate.getDate()+1);
            jQuery('#sys_txt_date_out2, #sys_txt_date_out2_1').removeAttr('disabled');
            jQuery("#sys_txt_date_out2, #sys_txt_date_out2_1").datepicker("option", "minDate", selectDate);
            if(!jQuery("#sys_txt_date_out2").val()){
                jQuery("#sys_txt_date_out2").datepicker("setDate", selectDate);
            }
            if(!jQuery("#sys_txt_date_out2_1").val()){
                jQuery("#sys_txt_date_out2_1").datepicker("setDate", selectDate);
            }
        }
    });
    jQuery("#sys_txt_date_out2, #sys_txt_date_out2_1").datepicker({
        dateFormat:"dd-mm-yy",
        changeMonth:false,
        firstDay:1,
        minDate:0
    });

    $(".wrap-input-date label").click(function(e) {
        var id = $(this).data('inputid');
        if ($('#'+id).datepicker('widget').is(':hidden')) {
            $('#'+id).datepicker("show").datepicker("widget").show();
        } else {
            //$('#'+id).hide();
        }
    });

    //REVIEW
    hotel_id = $('#hotel_id').val();
    jQuery.post(WEB_DIR + "ajax.php?act=hotel_review&code=all_review", {
        cus_type:0,
        hotel_id:hotel_id
    }, function (review) {
        number_reviews = Object.keys(review).length;
        //Giới hạn số review
        if (number_reviews > 3) {
            number_reviews = 3;
        }
        for (i = 0; i < number_reviews; i++) {
            var time = review[i].created_time;
            var date = new Date(time * 1000);
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            $('<div class="comment-item"><div class="comment-info"><strong>' + review[i].user_name + '</strong><span>|</span><span>' + review[i].address + '</span><span>-</span><span>' + day + '/' + month + '/' + year + '</span></div><div class="comment-content"><div class="quote"><h5>' + review[i].comment_title + '</h5><p>' + review[i].comment + '</p><span class="btn-score"><span class="counted">' + review[i].rating_0_point + '</span></span></div></div></div>').appendTo("#lst-comment");
        }
    }, "json");

    $(".view_more").click(function () {
        $(".view_more").hide();
        jQuery.post(WEB_DIR + "ajax.php?act=hotel_review&code=all_review", {
            cus_type:0,
            hotel_id:hotel_id
        }, function (review) {
            number_reviews = Object.keys(review).length;
            //Giới hạn số review
            if (number_reviews > 100) {
                number_reviews = 100;
            }
            for (i = 3; i < number_reviews; i++) {
                var date = new Date(review[i].created_time * 1000);
                var year = date.getFullYear();
                var month = date.getMonth() + 1;
                var day = date.getDate();
                $('<div class="comment-item"><div class="comment-info"><strong>' + review[i].user_name + '</strong><span>|</span><span>' + review[i].address + '</span><span>-</span><span>' + day + '/' + month + '/' + year + '</span></div><div class="comment-content"><div class="quote"><h5>' + review[i].comment_title + '</h5><p>' + review[i].comment + '</p><span class="btn-score"><span class="counted">' + review[i].rating_0_point + '</span></span></div></div></div>').appendTo("#lst-comment");
            }
        }, "json");
    });

    //Thêm đánh giá mới - Tú 23.11.2012

//    for (var a=1; a<7; a++){
    $(".sys_score").on("click", function () {
        var getIndex = parseInt($(this).attr("value-key"), 10);
        var getScore = parseInt($(this).parent().attr("sc-key"), 10);
        //span-yes
        $(this).addClass("span-yes").removeClass("span-non").siblings().each(function (idx, val) {
            if (parseInt($(val).attr("value-key")) < getIndex) {
                $(val).addClass("span-yes").removeClass("span-non");
            } else {
                $(val).addClass("span-non").removeClass("span-yes");
            }
            $(val).fadeOut(200).fadeIn(200).off("mouseover mouseout");
        });
        $(this).off("mouseover mouseout");
        $("#score_" + getScore).text(getIndex);
        calscore(getScore, getIndex);

    });
    $(".sys_score").on("mouseover", function () {
        var getIndex = parseInt($(this).attr("value-key"), 10);
        var getScore = parseInt($(this).parent().attr("sc-key"), 10);
        $(this).addClass("span-yes").removeClass("span-non").siblings().each(function (idx, val) {
            if (parseInt($(val).attr("value-key")) < getIndex) {
                $(val).addClass("span-yes").removeClass("span-non");
            }
        });
        $("#score_" + getScore).text(getIndex);
    });
    $(".sys_score").on("mouseout", function () {
        var getScore = $(this).parent().attr("sc-key");
        $(this).addClass("span-non").removeClass("span-yes").siblings().each(function (idx, val) {
            $(val).addClass("span-non").removeClass("span-yes");
        });
        $("#score_" + getScore).text(0);
    });

    $(".add-comment-textarea").mouseout(function () {
        if ($(".add-comment-title").val() != '' && $(".add-comment-textarea").val() != '') {
            $(".btn-send-comment").css("opacity", "1").css("cursor", "pointer");
        } else {
            $(".btn-send-comment").css("opacity", "0.5").css("cursor", "default");
        }
    });

    $(".btn-send-comment").click(function () {
        hotel_id = $('#hotel_id').val();
        review1 = $("#score_1").text();
        review2 = $("#score_2").text();
        review3 = $("#score_3").text();
        review4 = $("#score_4").text();
        review5 = $("#score_5").text();
        review6 = $("#score_6").text();
        title = $(".add-comment-title").val();
        content = $(".add-comment-textarea").val();

//        console.log(review1, review2, review3, review4, review5, review6, title, content, hotel_id);
        jQuery.post(WEB_DIR + "ajax.php?act=hotel_review&code=add_review", {
            score1:review1,
            score2:review2,
            score3:review3,
            score4:review4,
            score5:review5,
            score6:review6,
            title:title,
            content:content,
            cus_type:1,
            hotel_id:hotel_id
        }, function (msg) {
            if (msg == 1) {
                alert("Gửi bình luận thành công, nhận xét của bạn đang chờ được xét duyệt !");
                $(".add-comment").slideToggle(300);
            } else if (msg == 0) {
                /*alert("Lỗi :D");
                 $(".add-comment").slideToggle(300);*/
            } else if (msg == 2) {
                alert("Vui lòng đăng nhập để sử dụng tính năng này !")
            }
        });
    });

});

var totalpoint = 0;
var score1 = 0;
var score2 = 0;
var score3 = 0;
var score4 = 0;
var score5 = 0;
var score6 = 0;

function calscore(score, point) {//hàm tính điểm trung bình cho thêm review
    if (score == 1) score1 = parseInt(point);
    if (score == 2) score2 = parseInt(point);
    if (score == 3) score3 = parseInt(point);
    if (score == 4) score4 = parseInt(point);
    if (score == 5) score5 = parseInt(point);
    if (score == 6) score6 = parseInt(point);

    totalpoint = parseInt(score1 + score2 + score3 + score4 + score5 + score6);
    var num_score = 0;
    if (score1 != 0) num_score = parseInt(num_score + 1);
    if (score2 != 0) num_score = parseInt(num_score + 1);
    if (score3 != 0) num_score = parseInt(num_score + 1);
    if (score4 != 0) num_score = parseInt(num_score + 1);
    if (score5 != 0) num_score = parseInt(num_score + 1);
    if (score6 != 0) num_score = parseInt(num_score + 1);

//    console.log(totalpoint);
//    console.log(num_score);
    if (totalpoint > 0 && num_score > 0) {
        totalpoint = totalpoint / num_score;
        $(".btn-score-ac").show();
        $(".counted-ac").text(totalpoint.toFixed(1));

        if (totalpoint >= 9) $(".counted-ac2").text("- Xuất sắc");
        else if (totalpoint >= 8 && totalpoint < 9) $(".counted-ac2").text("- Tuyệt vời");
        else if (totalpoint >= 6 && totalpoint < 8) $(".counted-ac2").text("- Rất tốt");
        else if (totalpoint >= 5 && totalpoint < 6) $(".counted-ac2").text("- Khá tốt");
        else $(".counted-ac2").text("- Tạm được");
    }
}

function addPeriod(nStr)//Hàm format số tiền
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    }
    return x1 + x2;
}

function datetostring(myDate) {
    myDate = myDate.split("-");
    var newDate = myDate[1] + "/" + myDate[0] + "/" + myDate[2];
    return (new Date(newDate).getTime());
}